package com.ee.chat.api.task;

import com.ee.chat.api.common.CommonService;
import com.ee.chat.common.dao.UserMapper;
import com.ee.chat.common.dao.UserOnlineLogMapper;
import com.ee.chat.common.entity.User;
import com.ee.chat.common.entity.UserOnlineLog;
import com.ee.chat.common.util.ConstantsUtil;
import com.ndhutu.ee.util.DateUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class UserStatusTask {
    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;
    @Resource
    UserMapper userMapper;
    @Resource
    CommonService commonService;
    @Resource
    UserOnlineLogMapper userOnlineLogMapper;

    /**
     * 更新用户在线状态，半小时执行一次
     * @Author Shane
     * @Date 2019/11/21 10:38
     * @param
     * @return
     **/
    @Scheduled(cron = "0 0/30 * * * ?")
    public void updateUserStatus() throws Exception{
        if(!commonService.getIpStatus()){
            return;
        }

        Set<String> keys = redisTemplate.keys(ConstantsUtil.USER_ONLINE+"*");
        for(String key : keys){
            Map<Object, Object> map = redisTemplate.boundHashOps(key).entries();
            if(map == null){
                continue;
            }
            Date time = DateUtil.parse(map.get("time")+"");
            Integer status = Integer.parseInt(map.get("status")+"");
            if(System.currentTimeMillis() - time.getTime() > 1*60*60*1000 && !status.equals(2)){    //用户下线
                redisTemplate.expire(key, -1, TimeUnit.MINUTES);

                //更新用户状态，下线
                int userId = Integer.parseInt(key.replaceAll(ConstantsUtil.USER_ONLINE, ""));
                User user = new User();
                user.setId(userId);
                user.setOnline(0);
                userMapper.updateById(user);

                //失效在线时间
                redisTemplate.expire(ConstantsUtil.USER_ONLINE + userId, -1, TimeUnit.MINUTES);

                //下线记录时间
                UserOnlineLog userOnlineLog = userOnlineLogMapper.selectNewestLog(userId);
                userOnlineLog.setDownTime(new Date());
                userOnlineLogMapper.updateById(userOnlineLog);

                //失效同城打招呼
                Set<String> callKeys = redisTemplate.keys(ConstantsUtil.USER_LOCAL_SAYHELLO + userId+":*");
                for(String callKey : callKeys){
                    redisTemplate.expire(callKey, -1, TimeUnit.MINUTES);
                }

                //清空用户已返回的随机在线主播数据
                redisTemplate.expire(ConstantsUtil.USER_HISTORY_RANDOM+":"+userId, -1, TimeUnit.MINUTES);

            }
        }
    }

}
